package com.lwl.handler;

import com.lwl.pojo.RpcConnectPojo;
import com.lwl.zk.ZookeeperUtils;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ZookeeperWatcher {
    //存储活动状态的连接
    public static Map<String, RpcConnectPojo> serviceMap = new ConcurrentHashMap<>();

    //设置服务端节点监听
    public static void setWatcher(Set<String> list) {
        ZkClient session = ZookeeperUtils.getSession();
        //设置对子节点的监听
        for (String key : list) {
            System.out.println("对节点" + key + "设置节点监听");
            //监听节点内容变化
            session.subscribeDataChanges(key, new IZkDataListener() {
                @Override
                public void handleDataChange(String s, Object o) throws Exception {
                }
                //节点删除，断开服务器
                @Override
                public void handleDataDeleted(String s) throws Exception {
                    System.out.println(s + " 节点被删除！");
                    if (serviceMap.containsKey(s)) {
                        serviceMap.remove(s);
                    }
                }
            });
        }
    }
}
